package com.coszero.utils.utils

import android.R
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

/**
 * 内部判断App是否升级的管理类
 * 当需要升级时，不调用外部下载器，直接使用内部下载器下载应用。
 * @author coolszy
 * @date 2012-4-26
 * @blog http://blog.92coding.com
 * @version 1
 */
class UpdateManager
    (private val mContext: Context) {
    /* 保存解析的XML信息 */
    var mHashMap: HashMap<String, String>? = null

    /* 下载保存路径 */
    private var mSavePath: String? = null

    /* 记录进度条数量 */
    private var progress: Int = 0

    /* 是否取消更新 */
    private var cancelUpdate: Boolean = false

    /* 更新进度条 */
    private var mProgress: ProgressBar? = null
    private var mDownloadDialog: Dialog? = null

    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                DOWNLOAD ->                     // 设置进度条位置
                    mProgress!!.setProgress(progress)

                DOWNLOAD_FINISH ->                     // 安装文件
                    installApk()

                else -> {}
            }
        }
    }

    private val mHandlerIsUpdate: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> showNoticeDialog()
                2 ->                     //if(mContext.getClass().getSimpleName().equals("SettingFragment")){
                    Toast.makeText(mContext, "已经是最新版本!", Toast.LENGTH_LONG).show()

                else -> {}
            }
        }
    }

    /**
     * 检测软件更新
     */
    fun checkUpdate(ShowMsg: Int) {
        object : MyThread(ShowMsg) {
            override fun run() {
                // 获取当前软件版本

                val versionCode: Int = getVersionCode(mContext)


                // 把version.xml放到网络上，然后获取文件信息
                //InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream(R.string.server_url + "version.xml");
                val this_url: URL
                var inStream: InputStream? = null
                try {
//                    下载地址
                    this_url = URL("http://" + "/c/version.xml")
                    inStream = this_url.openConnection().getInputStream()
                } catch (e1: IOException) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace()
                }


                // 解析XML文件。 由于XML文件比较小，因此使用DOM方式进行解析
//                ParseXmlService service = new ParseXmlService();
                try {
//                    mHashMap = service.parseXml(inStream);
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                if (null != mHashMap) {
                    val serviceCode: Int = mHashMap!!.get("version")!!.toInt()
                    // 版本判断
                    if (serviceCode > versionCode) {
                        mHandlerIsUpdate.sendEmptyMessage(1)
                    } else {
                        if (GetShowMsg() == 1) {
                            mHandlerIsUpdate.sendEmptyMessage(2)
                        }
                    }
                } else {
                    if (GetShowMsg() == 1) {
                        mHandlerIsUpdate.sendEmptyMessage(2)
                    }
                }
            }
        }.start()
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private fun getVersionCode(context: Context): Int {
        var versionCode: Int = 0
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager()
                .getPackageInfo("com.db.surfing_car_friend", 0).versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return versionCode
    }

    /**
     * 显示软件更新对话框
     */
    private fun showNoticeDialog() {
        // 构造对话框
        val builder: AlertDialog.Builder = AlertDialog.Builder(mContext)
        builder.setTitle("软件更新")
        //builder.setMessage(R.string.soft_update_info);
        builder.setMessage(mHashMap!!.get("content").toString())
        // 更新
        builder.setPositiveButton("确定更新", object : DialogInterface.OnClickListener {
            override fun onClick(dialog: DialogInterface, which: Int) {
                dialog.dismiss()
                // 显示下载对话框
                showDownloadDialog()
            }
        })
        // 稍后更新
        builder.setNegativeButton("稍后更新", object : DialogInterface.OnClickListener {
            override fun onClick(dialog: DialogInterface, which: Int) {
                dialog.dismiss()
            }
        })
        val noticeDialog: Dialog = builder.create()
        noticeDialog.show()
    }

    /**
     * 显示软件下载对话框
     */
    private fun showDownloadDialog() {
        // 构造软件下载对话框
        val builder: AlertDialog.Builder = AlertDialog.Builder(mContext)
        builder.setTitle("更新提醒")
        // 给下载对话框增加进度条
        val inflater: LayoutInflater = LayoutInflater.from(mContext)
        //重新设置下载进度条
        @SuppressLint("ResourceType") val v: View = inflater.inflate(1, null)
        mProgress = v.findViewById<View>(R.id.progress) as ProgressBar?
        builder.setView(v)
        // 取消更新
        builder.setNegativeButton("取消", object : DialogInterface.OnClickListener {
            override fun onClick(dialog: DialogInterface, which: Int) {
                dialog.dismiss()
                // 设置取消状态
                cancelUpdate = true
            }
        })
        mDownloadDialog = builder.create()
        mDownloadDialog.show()
        // 现在文件
        downloadApk()
    }

    /**
     * 下载apk文件
     */
    private fun downloadApk() {
        // 启动新线程下载软件
        downloadApkThread().start()
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private inner class downloadApkThread : Thread() {
        override fun run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                    // 获得存储卡的路径
                    val sdpath: String = Environment.getExternalStorageDirectory().toString() + "/"
                    mSavePath = sdpath + "download"
                    val url: URL = URL(mHashMap!!.get("url"))
                    // 创建连接
                    val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
                    conn.connect()
                    // 获取文件大小
                    val length: Int = conn.getContentLength()
                    // 创建输入流
                    val `is`: InputStream = conn.getInputStream()

                    val file: File = File(mSavePath)
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir()
                    }
                    val apkFile: File = File(mSavePath, mHashMap!!.get("name"))
                    val fos: FileOutputStream = FileOutputStream(apkFile)
                    var count: Int = 0
                    // 缓存
                    val buf: ByteArray = ByteArray(1024)
                    // 写入到文件中
                    do {
                        val numread: Int = `is`.read(buf)
                        count += numread
                        // 计算进度条位置
                        progress = ((count.toFloat() / length) * 100).toInt()
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD)
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH)
                            break
                        }
                        // 写入文件
                        fos.write(buf, 0, numread)
                    } while (!cancelUpdate) // 点击取消就停止下载.
                    fos.close()
                    `is`.close()
                }
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            // 取消下载对话框显示
            mDownloadDialog!!.dismiss()
        }
    }

    /**
     * 安装APK文件
     */
    private fun installApk() {
        val apkfile: File = File(mSavePath, mHashMap!!.get("name"))
        if (!apkfile.exists()) {
            return
        }
        // 通过Intent安装APK文件
        val i: Intent = Intent(Intent.ACTION_VIEW)
        i.setDataAndType(
            Uri.parse("file://" + apkfile.toString()),
            "application/vnd.android.package-archive"
        )
        mContext.startActivity(i)
    }

    open inner class MyThread(private val ShowMsg: Int) : Thread() {
        fun GetShowMsg(): Int {
            return ShowMsg
        }
    }

    companion object {
        /* 下载中 */
        private const val DOWNLOAD: Int = 1

        /* 下载结束 */
        private const val DOWNLOAD_FINISH: Int = 2
    }
}